const fs = require('fs-extra');
const path = require('path');
const archiver = require('archiver');

const NAMESPACE = require('../package.json').name;
const workspace = process.cwd();
const RELEASE_PATH = path.resolve(workspace, './release');
const OUTPUT_PATH = path.resolve(workspace, './output');
const ZIP_PATH = path.resolve(workspace, './output-zip');

const WIN_APP_NAME = `${NAMESPACE}-win`;
const LINUX_APP_NAME = `${NAMESPACE}-linux`;
const MACOS_APP_NAME = `${NAMESPACE}-macos`;

const list = [
	{
		system: 'app-win',
		name: WIN_APP_NAME
	},
	{
		system: 'app-linux',
		name: LINUX_APP_NAME
	},
	{
		system: 'app-macos',
		name: MACOS_APP_NAME
	}
];

(async () => {
	await fs.remove(OUTPUT_PATH);
	await fs.remove(ZIP_PATH);

	for (const app of list) {
		const { name, system } = app;
		const filename = (name === WIN_APP_NAME ? name + '.exe' : name);
		const TARGET_PATH = path.join(OUTPUT_PATH, system, filename);
		const ORIGIN_APP_PATH = path.join(RELEASE_PATH, filename);

		await fs.move(ORIGIN_APP_PATH, TARGET_PATH);
	}

	await fs.ensureDir(ZIP_PATH);

	const ZIP_FILE_PATH = path.join(ZIP_PATH, 'output.zip');

	await toZip(OUTPUT_PATH, ZIP_FILE_PATH);

	await fs.remove(RELEASE_PATH);
})();

async function toZip(source, target) {
	const writeStream = fs.createWriteStream(target);
	const archive = archiver('zip', { zlib: { level: 9 } });

	archive.pipe(writeStream);
	archive.directory(source, false);
	archive.finalize();

	return new Promise((resolve, reject) => {
		writeStream.on('finish', () => {
			resolve();
		});

		writeStream.on('error', (error) => {
			reject(error);
		});
	});
}